package org.ws.httphelper.example.builder;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.gargoylesoftware.htmlunit.util.UrlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.ws.httphelper.HttpHelper;
import org.ws.httphelper.model.http.ResponseFuture;

import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class BuilderSampleServiceImp implements BuilderSampleService {

    @Autowired
    private HttpHelper searchImgHttp;

    @Autowired
    private HttpHelper saveImgHttp;

    @Override
    public void searchAndDownload(String url) {
        // 执行请求
        ResponseFuture responseFuture = searchImgHttp.request(url);
        log.info(JSON.toJSONString(responseFuture, SerializerFeature.PrettyFormat));
        if(responseFuture.isSuccess()){
            Map output = (Map)responseFuture.getOutput();
            // 获取解析的URL
            List<String> imageList = (List<String>)output.get("imageList");
            if(CollectionUtils.isNotEmpty(imageList)){
                for (String img : imageList) {
                    if(StringUtils.isNotBlank(img)) {
                        final String imgUrl=UrlUtils.resolveUrl(url,img);
                        // 执行保存
                        saveImgHttp.requestAsync(imgUrl, future -> {
                            log.info("save {} -> {}", imgUrl, future.isSuccess());
                        });
                    }
                }
            }
        }
    }
}
